package com.faithnmn.learnenglishbc.network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.faithnmn.learnenglishbc.R;
import com.faithnmn.learnenglishbc.util.Constants;
import com.faithnmn.learnenglishbc.util.StorageUtil;

public class Downloader extends AsyncTask<String, Integer, Boolean> {

	private static final String homeFolder = StorageUtil.AUDIO_FOLDER;
	private File outputFile = null;
	private Context mContext;
	private NotificationManager notiHelper;
	private int NOTIFICATION_ID = 223;
	private String lessionTitle,audioName;
	private Intent sendProgress;
	private DownloadCompleteCallback downloadCompleteCallback;
	public Downloader(Context context) {
		mContext = context;
		notiHelper = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		sendProgress = new Intent(Constants.DOWNLOAD_PROGRESS);
	}

	@Override
	protected Boolean doInBackground(String... aurl) {
		lessionTitle = aurl[1];
		audioName = aurl[2];
		return download(aurl[0]);
	}

	// update notify
	@Override
	protected void onProgressUpdate(Integer... progress) {
		sendProgress.putExtra("progress", progress[0]);
		LocalBroadcastManager.getInstance(mContext).sendBroadcast(sendProgress);
		displayNotification("\u0110ang t\u1EA3i d\u1EEF li\u1EC7u.."+progress[0]+" %",null);
	}

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected void onPostExecute(Boolean result) {
		Intent sendResult = new Intent(Constants.NOTIFY_AUDIO_READY_ACTION);
		sendResult.putExtra("lessionTitle", lessionTitle);
		sendResult.putExtra("audioName", audioName);
		if (result) {
			Log.e("Downloader", "download english episode complete "+lessionTitle);
			displayNotification("\u0110\u00E3 l\u01B0u \u00E2m thanh - "+lessionTitle,"Th\u00F4ng b\u00E1o");
			sendResult.putExtra("done", true);
		} else {
			Log.e("Downloader", "download english episode fail "+lessionTitle);
			displayNotification("L\u1ED7i t\u1EA3i \u00E2m thanh - "+lessionTitle,"Th\u00F4ng b\u00E1o");
			sendResult.putExtra("done", false);
		}
		if(downloadCompleteCallback != null){
			downloadCompleteCallback.onDownloadComplete(audioName);
		}
		mContext.sendBroadcast(sendResult);
	}
	
	protected void displayNotification(String message,String title) {
	      NotificationCompat.Builder  mBuilder = 
	      new NotificationCompat.Builder(mContext);	
	      mBuilder.setContentTitle(title == null?"\u0110ang l\u01B0u \u00E2m thanh..":title);
	      mBuilder.setContentText(message);
	      mBuilder.setTicker("\u0110ang l\u01B0u \u00E2m thanh..");
	      mBuilder.setSmallIcon(R.drawable.ic_launcher);
	      /* Increase notification number every time a new notification arrives */
//	      mBuilder.setNumber(++numMessages);
	      /* Creates an explicit intent for an Activity in your app */
//	      Intent resultIntent = new Intent(mContext, NotificationView.class);
//	      TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
//	      stackBuilder.addParentStack(NotificationView.class);
	      /* Adds the Intent that starts the Activity to the top of the stack */
//	      stackBuilder.addNextIntent(resultIntent);
//	      PendingIntent resultPendingIntent =
//	         stackBuilder.getPendingIntent(
//	            0,
//	            PendingIntent.FLAG_UPDATE_CURRENT
//	         );
//	      mBuilder.setContentIntent(resultPendingIntent);
	      mBuilder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
	      /* notificationID allows you to update the notification later on. */
	      notiHelper.notify(NOTIFICATION_ID, mBuilder.build());
	   }

	private boolean download(String urlStr) {
		int count;
		try {
			// folder
			String path = homeFolder;
			File sdAppMainDirectory = new File(path);
			sdAppMainDirectory.mkdirs();
			// file dowload
			String appName = "";
			appName = urlStr.substring(urlStr.lastIndexOf("/") + 1);
			outputFile = new File(sdAppMainDirectory, appName);
			// download
			String part1 = urlStr.substring(0, urlStr.lastIndexOf("/") + 1);
			String part2 = urlStr.substring(urlStr.lastIndexOf("/") + 1);
			part2 = part2.replace(" ", "%20");
			part2 = URLEncoder.encode(part2);
			part2 = part2.replaceAll("%2520", "%20");
			urlStr = part1 + part2;
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			int lenghtOfFile = connection.getContentLength();
			InputStream input = connection.getInputStream();
			OutputStream output = new FileOutputStream(outputFile);

			byte data[] = new byte[1024];
			long total = 0;
			int precent = -1;
			int downloadedCurrent = 0;
			while ((count = input.read(data)) != -1) {
				downloadedCurrent = (int) ((total * 100) / lenghtOfFile);
				total += count;
				if (precent != downloadedCurrent) {
					publishProgress(downloadedCurrent);
					precent = downloadedCurrent;
				}
				output.write(data, 0, count);
			}

			output.flush();
			output.close();
			input.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public void setDownloadCompleteListener(DownloadCompleteCallback downloadCompleteCallback){
		this.downloadCompleteCallback = downloadCompleteCallback;
	}
	
	public interface DownloadCompleteCallback{
		public void onDownloadComplete(String audioName);
	}
}